package fr.charlott.view.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import fr.charlott.business.dto.CategorieDTO;
import fr.charlott.business.service.CategorieService;

@Component("categorieConverter")
@FacesConverter("categorieConverter")
public class CategorieConverter implements Converter {

    private static CategorieService categorieService;

    public CategorieConverter() {
        super();
    }

    @Autowired(required = true)
    public CategorieConverter(CategorieService categorieService) {
        super();
        CategorieConverter.categorieService = categorieService;
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        return categorieService.chercherParNom(value);
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value instanceof CategorieDTO) {
            CategorieDTO categorieDTO = (CategorieDTO) value;
            return "" + categorieDTO.getNom();
        } else if (value instanceof Long) {
            return "" + value;
        } else {
            throw new IllegalArgumentException("Cannot convert");
        }
    }
}
